package co.sanduche.views;

import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import co.sanduche.R;
import co.sanduche.app.SanducheApp;
import co.sanduche.services.EPClient;

public abstract class BasicSplashScreenActivity extends Activity implements
		OnClickListener {

	private ImageView imageView;
	private Handler handler;

	/**
	 * Time out del splash. Puede ser sobreescrito por una subclase via
	 * {@link #getSplashTimeout()}
	 */
	public static int SPLASH_TIME_OUT = 500000000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i("Test", "Crea el splash");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash_screen);

		imageView = (ImageView) findViewById(R.id.splashImgLogo);
		imageView.setImageResource(getSplashImageId());
		imageView.setOnClickListener(this);

		TextView textView = (TextView) findViewById(R.id.splashVersion);
		textView.setText(getVersion());

		View root = imageView.getRootView();
		root.setBackgroundColor(getResources().getColor(
				getSplashBackgroundColorId()));
		handler = new Handler();
		handler.postDelayed(new Runnable() {

			/*
			 * Showing splash screen with a timer. This will be useful when you
			 * want to show case your app logo / company
			 */

			@Override
			public void run() {
				checkNext();
			}
		}, getSplashTimeout());
		finishCreate();
	}

	public abstract void finishCreate();

	public abstract String getVersion();

	public abstract int getSplashBackgroundColorId();

	@Override
	protected void onResume() {
		super.onResume();
	}

	public void showError(String message) {
		// TODO Auto-generated method stub

	}

	public void checkNext() {
		// check if it is logged
		try {
			HttpCookie cookie = SanducheApp
					.getInstance()
					.getCookieHandler()
					.getCookie(
							new URI(EPClient.getDevPhase().server).getHost(),
							EPClient.AUTH_COOKIE);
			Intent i = null;
			if (cookie != null)
				i = new Intent(this, getNextActivityClass());
			else
				i = new Intent(this, getLoginActivityClass());
			startActivity(i);
			finish();

		} catch (URISyntaxException e) {
			// It should never happen
			e.printStackTrace();
		}
	}

	public abstract Class<? extends Activity> getNextActivityClass();

	public abstract Class<? extends Activity> getLoginActivityClass();

	@Override
	public void onClick(View v) {
		handler.removeCallbacks(null);
		checkNext();
	}

	public int getSplashTimeout() {
		return SPLASH_TIME_OUT;
	}

	public abstract int getSplashImageId();
}
